/**
 * 
 */
package com.thon.dao.user.impl;


import java.util.Date;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.thon.dao.user.LetterDao;
import com.thon.dao.util.AbstractDao;
import com.thon.dao.util.Page;
import com.thon.entity.user.Letter;

/**
 * @file LetterDaoImpl.java
 * @author Zemo
 * @email zemochen@lanbaoo.com
 * @date 2013年12月10日 下午10:10:49
 * @description TODO
 */
@Repository
public class LetterDaoImpl extends AbstractDao<Letter> implements LetterDao{
	
	public LetterDaoImpl(){
		super(Letter.class);
	}

	@Override
	public Page<Letter> listOldLetters(Page<Letter> page, Integer userId,
			Integer friendId,Date date) {
		
		String queryString = "FROM Letter l WHERE l.userId=? AND l.friendId=?  ORDER BY l.createdDate DESC";
		return findPage(page, queryString, userId,friendId);
	}

	@Override
	public List<Object> listFriends(Integer userId) {
		
		String sqlString = "SELECT friend_id ,MAX(id) AS msg_id FROM ym_letters l WHERE user_id=? GROUP BY friend_id ORDER BY msg_id DESC";
		return findListBySql(sqlString, userId);
	}

	@Override
	public Page<Letter> listNewLetters(Page<Letter> page, Integer userId,
			Integer friendId, Date date) {

		String queryString = "FROM Letter l WHERE l.userId=? AND l.friendId=? AND l.isRead = 0 ORDER BY l.id DESC";
		return findPage(page, queryString, userId,friendId);
	}

	@Override
	public Long countLetter(Integer isRead, Integer userId) {
		
		String queryString = "SELECT COUNT(*) FROM Letter WHERE isRead = ? AND letterTo = ? AND userId = ?";
		return count(queryString, isRead,userId,userId);
	}

	@Override
	public Page<Letter> findNewLetters(Page<Letter> page, Integer userId) {
		String queryString="SELECT * FROM ym_letters WHERE id IN (SELECT MAX(id) AS maxid FROM ym_letters WHERE user_id=? GROUP BY friend_id) ORDER BY id DESC";
		return findPageBySql(page, queryString, null, userId);
	}
 }
